package it.koutifaris.travianmap.view.distances;

import it.koutifaris.travianmap.context.ContextRetreiver;
import it.koutifaris.travianmap.geometry.DistanceCalculator;
import it.koutifaris.travianmap.geometry.Point;
import it.koutifaris.travianmap.model.Village;
import it.koutifaris.travianmap.utils.VillageToPoint;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class VillagesSpinnerAdapter extends ArrayAdapter<Village> {

	private final Point center;

	public VillagesSpinnerAdapter(Context context, Point center, List<Village> villageList) {
		super(context, android.R.layout.simple_spinner_item);

		this.center = center;

		List<Village> villages = new ArrayList<Village>(villageList);
		Collections.sort(villages, new DistanceComparator(center));

		for (Village village : villages) {
			this.add(village);
		}

	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		TextView view = (TextView) super.getView(position, convertView, parent);
		Village village = getItem(position);
		view.setText(village.getName());

		return view;
	}

	@Override
	public View getDropDownView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		TextView view;

		if (convertView == null) {
			view = (TextView) inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
		} else {
			view = (TextView) convertView;
		}

		Village village = getItem(position);
		view.setText(village.getName() + " -> " + getDistanceText(village));

		return view;
	}

	private String getDistanceText(Village village) {
		float distance = new DistanceCalculator(center, new VillageToPoint(village)).getDistance();
		NumberFormat format = ContextRetreiver.contextRetreiver().getCurrentContext().getLocaleSettings().getDefaultNumberFormat();

		return format.format(distance);
	}

	private static class DistanceComparator implements Comparator<Village> {

		private final Point center;

		public DistanceComparator(Point center) {
			this.center = center;
		}

		@Override
		public int compare(Village lhs, Village rhs) {
			float distanceA = new DistanceCalculator(center, new VillageToPoint(lhs)).getDistance();
			float distanceB = new DistanceCalculator(center, new VillageToPoint(rhs)).getDistance();

			return Math.round((distanceA - distanceB) * 1000);
		}

	}

}
